package com.ft.adbix.utils.http.listener;

import com.ft.adbix.core.bean.HttpBean;
import com.ft.adbix.core.common.ErrorCode;
import com.ft.adbix.core.response.Ad;
import com.ft.adbix.utils.AdChecker;
import com.ft.adbix.utils.AdLogUtils;
import com.ft.adbix.utils.json.Gson;
import com.ft.adbix.utils.json.reflect.TypeToken;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public abstract class CommonAdListener implements HttpListener {

    @Override
    public void onRequestStart() {

    }

    @Override
    public void onRequestFailed(int code, String error) {
        AdLogUtils.d("onRequestFailed code = " + code + "- msg = " + error);
        onError(code, error);
    }

    @Override
    public void onRequestSuccess(String result) {
        AdLogUtils.d("onRequestSuccess 11" + result);
        try {
//            Type type = getClass().getGenericSuperclass();
//            if (type instanceof ParameterizedType){
//                i((ParameterizedType) type).getActualTypeArguments()[0];
//            }
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.getInt("code")!=200){
                int code = jsonObject.getInt("code");
                String message = jsonObject.getString("message");
                onError(code, message);
                return;
            }
            Type type = new TypeToken<HttpBean<Ad>>() {
            }.getType();
            HttpBean<Ad> response = new Gson().fromJson(result, type);
            Ad ad = response.getData();
            if (!AdChecker.checkAdEnable(ad)) {
                onError(ErrorCode.ERROR_AD_INFO_NOT_FULL, "广告数据不完整");
                return;
            }
            onResponse(ad);
        } catch (Exception e) {
            e.printStackTrace();
            onError(ErrorCode.ERROR_AD_DATA_ANALYZE_FAILED, "广告数据解析异常");
        }
    }

    @Override
    public void onRequestSuccess(String result, Map<String, List<String>> responseHeader) {
        AdLogUtils.d("onRequestSuccess 22" + result);
    }

    public abstract void onResponse(Ad result);

    public abstract void onError(int code, String error);

}
